﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Drawing;
using CMS.Utils.Drawing.Imaging;
using CMS.Utils.Extension;
using CMS.Services;
using System.Web.Mvc;
using CMS.BL.Entity;

namespace ECULineAnniversary.Web.Mvc
{
    /// <summary>
    /// Summary description for Handler1
    /// </summary>
    public class Handler1 : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string location = context.Request["image"];

            if (location == null)
                throw new HttpException("Invalid request.");

            string extension;
            string contentType;

            try
            {
                extension = Path.GetExtension(location).ToLower();
            }
            catch
            {
                throw new HttpException("Invalid request.");
            }

            if (extension == ".jpg")
                contentType = "image/jpeg";
            else if (extension == ".jpeg")
                contentType = "image/jpeg";
            else if (extension == ".png")
                contentType = "image/png";
            else if (extension == ".gif")
                contentType = "image/gif";
            else if (extension == ".bmp")
                contentType = "image/bmp";
            else
                throw new HttpException(404,"Invalid request.");


            string absoluteLocation = HttpContext.Current.Server.MapPath("~/" + location);
            
            //var config = ImageProviderWebSectionGroup.FromCurrentConfiguration().ImageProvider;
            //if (config.Presets.Count == 0)
            //    throw new ConfigurationErrorsException("No resize presets defined.");
            //ImageProviderPresetElement preset;

            tbl_ProdImageVerNames preset = new tbl_ProdImageVerNames();
            if (context.Request["preset"] != null)
            {

                if (preset == null)
                    throw new ArgumentException("The specified preset name is not valid.", "preset");
            }

            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.SetExpires(DateTime.Now.AddDays(3));

            if (preset.VN_Width == 0 && preset.VN_Width == 0)
            {
                context.Response.ContentType = contentType;

                using (FileStream F = File.OpenRead(absoluteLocation))
                {
                    F.Write(context.Response.OutputStream, 65536);
                }

                return;
            }

            string absoluteCacheDirectoryLocation = 
                context.Server.MapPath(String.IsNullOrEmpty(preset.VN_Path) ? "/Images/Versions" : preset.VN_Path.TrimEnd('/'));

            string absoluteCacheFileLocation =
                absoluteCacheDirectoryLocation + Path.DirectorySeparatorChar +
                preset.VN_Width.ToString() + "x" + preset.VN_Height.ToString() +
                "_" + ((ImageResizer.ResizeMode)Enum.Parse(typeof(ImageResizer.ResizeMode), preset.VN_Mode.GetValueOrDefault((int)ImageResizer.ResizeMode.CropToDestinationAspect).ToString())).ToString() + 
                "_" + Path.GetFileName(location);

            if (File.Exists(absoluteCacheFileLocation))
            {
                context.Response.ContentType = contentType;

                using (FileStream F = File.OpenRead(absoluteCacheFileLocation))
                {
                    F.Write(context.Response.OutputStream, 65536);
                }

                return;
            }

            using (ImageResizer resizer = new ImageResizer(absoluteLocation))
            {
                resizer.Background = String.IsNullOrEmpty(preset.VN_Background) ? ColorTranslator.FromHtml("#FFF") : ColorTranslator.FromHtml(preset.VN_Background);
                resizer.Mode = preset.VN_Mode.HasValue ? (ImageResizer.ResizeMode)Enum.Parse(typeof(ImageResizer.ResizeMode), preset.VN_Mode.Value.ToString()) : ImageResizer.ResizeMode.CropToDestinationAspect;
                resizer.Width = preset.VN_Width;
                resizer.Height = preset.VN_Height;

                resizer.Process();

                context.Response.ContentType = contentType;

                if (!Directory.Exists(absoluteCacheDirectoryLocation))
                    Directory.CreateDirectory(absoluteCacheDirectoryLocation);

                using (MemoryStream output = new MemoryStream())
                {
                    resizer.SaveAs(output);
                    output.WriteTo(context.Response.OutputStream);
                }

                resizer.SaveAs(absoluteCacheFileLocation);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}